import { SET_LIST, ADD_MESS_ITEM, ADD_CAR_ITEM, SUB_CAR_ITEM, DELETE_CAR_ITEM, SWITCH_CAR_ITEM_CHECK } from './actionsType'

const initState = {
	list: [],
	car: []
}


const reducer = (state = initState, action) => {
	const { type, payload } = action
	const { list, car } = state
	switch(type) {
		// 设置主页列表
		case SET_LIST:
			return {
				...state,
				list: payload
			};
		// 添加评论
		case ADD_MESS_ITEM:
			// 通过id 找到对应的数据
			const o = list.find(v => v.id === payload.id)
			// 头部推入新的数据
			o.mess.unshift(payload.data)
			return {
				...state,
				list: [...list]
			};
		// 添加购物车
		case ADD_CAR_ITEM: 
			{
				const newCar = [...car]
				const o = newCar.find(v => v.id === payload.id)
				if(o) {
					o.count++
				} else {
					newCar.unshift({
						...payload,
						count: 1,
						isChecked: false
					})
				}

				return {
					...state,
					car: [...newCar]
				}
			};
		case SUB_CAR_ITEM: 
			{
				const newCar = [...car]
				const o = newCar.find(v => v.id === payload.id)
				o.count--

				return {
					...state,
					car: [...newCar]
				}
			};
		case DELETE_CAR_ITEM:
			{
				const newCar = car.filter(v=> v.id !== payload.id)
				return {
					...state,
					car: [...newCar]
				}
			};
		case SWITCH_CAR_ITEM_CHECK: 
			{
				const newCar = [...car]
				const o = newCar.find(v => v.id === payload.id)
				o.isChecked = !o.isChecked
				return {
					...state,
					car: [...newCar]
				}
			};
		default:
			return state
	}
}


export default reducer

